package com.work.game.home.ui.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.android.volley.Request;
import com.anythink.nativead.api.ATNativeAdView;
import com.google.gson.Gson;
import com.work.game.R;
import com.work.game.ad.MediationFeedAd;
import com.work.game.ad.MediationRewardAd;
import com.work.game.ad.MediationTablePlaqueAd;
import com.work.game.ad.inter.RewardAdInter;
import com.work.game.ad.kaku.banner.TaKuBannerAdWithdrawal;
import com.work.game.ad.kaku.interstitia.TaKuInterstitialAdWithdrawal;
import com.work.game.ad.kaku.reward.TaKuRewardAd;
import com.work.game.ad.kaku.reward.TaKuRewardAdWithdrawal;
import com.work.game.config.UrlConfig;
import com.work.game.home.ui.adapter.MoneyGridViewAdapter;
import com.work.game.home.ui.enums.AdStatusEnum;
import com.work.game.home.ui.enums.MoneyTypeEnum;
import com.work.game.home.ui.enums.RedisEnum;
import com.work.game.home.ui.inter.InterWithdrawalConfig;
import com.work.game.home.ui.model.WithdrawalConfig;
import com.work.game.home.ui.model.vo.UserDailyActivityVo;
import com.work.game.home.ui.model.vo.WithdrawalRecordVo;
import com.work.game.home.ui.model.vo.WithdrawalVo;
import com.work.game.home.ui.model.vo.ZfInfoVo;
import com.work.game.utils.StringSplit;
import com.work.game.utils.risk.DeviceUtils;
import com.work.game.utils.risk.RiskUtils;
import com.work.game.utils.risk.VirtualApkCheckUtil;
import com.work.game.utils.usage.AppUsageHelper;
import com.work.game.view.MyGridView;
import com.work.game.volley.BaseActivity;
import com.work.game.volley.state.HUCState;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

public class WithdrawalActivity extends BaseActivity implements InterWithdrawalConfig, RewardAdInter {
    private MoneyGridViewAdapter moneyGridViewAdapter;
    private MyGridView gvMoney;
    private static final int REQUEST_USAGE_STATS = 1000;
    private EditText etName, etPhone;
    private AlertDialog alertDialog;
    private TextView tvMoneyGoldCoin, tvCurrentMoney, tvWithdrawalStatus;

    private WithdrawalVo withdrawalVo = new WithdrawalVo();
    private WithdrawalRecordVo withdrawalRecordVo = new WithdrawalRecordVo();
    /**
     * 变更后金额
     */
    private String afterMoney;

    private ATNativeAdView flFll;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_withdrawal);
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        if (intent != null) {
            // 其他数据类型可以使用 getIntExtra, getBooleanExtra 等方法
            String tag = intent.getStringExtra("tag");
            switch (Integer.valueOf(tag)) {
                case HUCState.HUC_REQEUST_CODE_1:
                    tvMoneyGoldCoin.setText(getSharedPreferences("moneyGoldCoin"));
                    tvActionbarTitle.setText("金币提现");
                    tvCurrentMoney.setText("当前金币");
                    break;
                case HUCState.HUC_REQEUST_CODE_2:
                    tvMoneyGoldCoin.setText(getSharedPreferences("moneyRedPacket"));
                    tvActionbarTitle.setText("红包提现");
                    tvCurrentMoney.setText("当前红包");
                    break;
                case HUCState.HUC_REQEUST_CODE_3:
                    tvMoneyGoldCoin.setText(getSharedPreferences(MoneyTypeEnum.MONEY_COMMISSION_GOLD_COINS.getKey()));
                    tvActionbarTitle.setText("金币佣金");
                    tvCurrentMoney.setText("当前金币佣金");
                    break;
                case HUCState.HUC_REQEUST_CODE_4:
                    tvMoneyGoldCoin.setText(getSharedPreferences(MoneyTypeEnum.MONEY_COMMISSION_RED_ENVELOPE.getKey()));
                    tvActionbarTitle.setText("红包佣金");
                    tvCurrentMoney.setText("当前红包佣金");
                    break;
                case HUCState.HUC_REQEUST_CODE_5:
                    tvMoneyGoldCoin.setText(getSharedPreferences(MoneyTypeEnum.MONEY_EXTENSION_RED_ENVELOPE.getKey()));
                    tvActionbarTitle.setText("推广佣金");
                    tvCurrentMoney.setText("当前推广佣金");
                    break;
            }
            String name = getSharedPreferences("afbName");
            if (StrUtil.isNotEmpty(name)) {
                tvWithdrawalStatus.setText("已绑定");
            }
            withdrawalVo.setType(tag);
            withdrawalRecordVo.setType(tag);
            loadWithdrawalConfig();
        }
        initAd();
    }

    @Override
    public void initView() {
        super.initView();
        gvMoney = findViewById(R.id.gv_money);
        tvMoneyGoldCoin = findViewById(R.id.tv_moneyGoldCoin);
        tvCurrentMoney = findViewById(R.id.tv_current_money);
        tvWithdrawalStatus = findViewById(R.id.tv_withdrawal_status);
        flFll = findViewById(R.id.fl_full);
    }

    @Override
    public void initClick() {
        super.initClick();
        findViewById(R.id.tv_withdrawal_record).setOnClickListener(this);
        findViewById(R.id.ll_pay_money).setOnClickListener(this);
        findViewById(R.id.tv_withdrawal).setOnClickListener(this);
        findViewById(R.id.tv_describe).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_withdrawal_record:
                sendIntent(this, WithdrawalRecordActivity.class, withdrawalRecordVo.getType());
                break;
            case R.id.ll_pay_money:
                showPayMoney();
                break;
            case R.id.tv_describe:
                showDescribe();
                break;
            case R.id.tv_withdrawal:
                if (!AppUsageHelper.isStatsEnabled(this)) {
                    AppUsageHelper.requestStats(this, REQUEST_USAGE_STATS);
                    return;
                }
                sendWithdrawal();
                break;
            default:
                break;
        }
    }

    private void sendWithdrawal() {
        String name = getSharedPreferences("afbName");
        if (StrUtil.isEmpty(name)) {
            showToast("请设置支付账号");
            return;
        }
        //验证提现额度
        String wcMoney = withdrawalRecordVo.getWcMoney();
        if (StrUtil.isEmpty(wcMoney)) {
            showToast("请选择提现金额");
            return;
        }
        Double money = Double.parseDouble(wcMoney);
        money = money * 10000;
        Integer beforeMoney = Integer.parseInt(tvMoneyGoldCoin.getText().toString());
        if (beforeMoney < money.intValue()) {
            showToast("余额不足，请重新选择");
            return;
        }
        afterMoney = String.valueOf(beforeMoney - money.intValue());
        if (AdStatusEnum.AD_STATUS_YES.getValue().equals(getSharedPreferences(RedisEnum.APP_ANSWER_WITHDRAWAL.getKey()))) {
            AlertDialog loadingDoaLog = showDialogLoading();
            String taKu = getSharedPreferences(RedisEnum.TA_KU.getKey());
            if (RedisEnum.TA_KU.getValue().equals(taKu)) {
               TaKuRewardAdWithdrawal taKuRewardAdWithdrawal = TaKuRewardAdWithdrawal.getInstance();
                taKuRewardAdWithdrawal.setToastContent("看完视频才能提现");
                taKuRewardAdWithdrawal.setAlertDialog(loadingDoaLog);
                taKuRewardAdWithdrawal.setContext(this);
                taKuRewardAdWithdrawal.setRewardAdInter(this);
                taKuRewardAdWithdrawal.setToken(getSharedPreferences("deviceId"));
                taKuRewardAdWithdrawal.showAd(this);
            } else {
                MediationRewardAd mediationRewardAd = MediationRewardAd.getInstance();
                mediationRewardAd.setActivity(this);
                mediationRewardAd.setRewardAdInter(this);
                mediationRewardAd.setToastContent("看完视频才能提现");
                mediationRewardAd.showCacheRewardAd(loadingDoaLog);
            }
        } else {
            applyWithdrawal();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_USAGE_STATS) {
            if (AppUsageHelper.isStatsEnabled(this)) {
                sendWithdrawal();
            } else {
                Toast.makeText(this, "未开启权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onSuccessfulStrType(int inputType, Object response) {
        super.onSuccessfulStrType(inputType, response);
        switch (inputType) {
            case HUCState.HUC_REQEUST_CODE_1:
                if (response instanceof List) {
                    List<WithdrawalConfig> withdrawalConfigList = (List<WithdrawalConfig>) response;
                    moneyGridViewAdapter = new MoneyGridViewAdapter(this, withdrawalConfigList, this);
                    gvMoney.setAdapter(moneyGridViewAdapter);
                }
                loadDismiss();
                break;
            case HUCState.HUC_REQEUST_CODE_2:
                if (response instanceof String) {
                    showToast((String) response);
                    setSharedPreferences("afbName", etName.getText().toString());
                    setSharedPreferences("afbPhone", etPhone.getText().toString());
                    alertDialog.dismiss();
                }
                loadDismiss();
                break;
            case HUCState.HUC_REQEUST_CODE_3:
                if (response instanceof String) {
                    Toast.makeText(this, (String) response, Toast.LENGTH_LONG).show();
                    String tag = withdrawalRecordVo.getType();
                    switch (Integer.valueOf(tag)) {
                        case HUCState.HUC_REQEUST_CODE_1:
                            setSharedPreferences("moneyGoldCoin", afterMoney);
                            tvMoneyGoldCoin.setText(afterMoney);
                            break;
                        case HUCState.HUC_REQEUST_CODE_2:
                            setSharedPreferences("moneyRedPacket", afterMoney);
                            tvMoneyGoldCoin.setText(afterMoney);
                            break;
                        case HUCState.HUC_REQEUST_CODE_3:
                            setSharedPreferences(MoneyTypeEnum.MONEY_COMMISSION_GOLD_COINS.getKey(), afterMoney);
                            tvMoneyGoldCoin.setText(afterMoney);
                            break;
                        case HUCState.HUC_REQEUST_CODE_4:
                            setSharedPreferences(MoneyTypeEnum.MONEY_COMMISSION_RED_ENVELOPE.getKey(), afterMoney);
                            tvMoneyGoldCoin.setText(afterMoney);
                            break;
                        case HUCState.HUC_REQEUST_CODE_5:
                            setSharedPreferences(MoneyTypeEnum.MONEY_EXTENSION_RED_ENVELOPE.getKey(), afterMoney);
                            tvMoneyGoldCoin.setText(afterMoney);
                            break;
                    }
                }
                loadDismiss();
                break;
        }
    }

    @Override
    public void selectPosition(WithdrawalConfig withdrawalConfig) {
        withdrawalRecordVo.setId(withdrawalConfig.getId());
        withdrawalRecordVo.setWcMoney(withdrawalConfig.getWcMoney());
    }

    @Override
    public void rewardAdSign(String ecpm) {
        applyWithdrawal();
    }

    private void showPayMoney() {
        //判断提现账号
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        // dialog.setTitle("绑定姓名");
        View root = LayoutInflater.from(this).inflate(R.layout.pop_pay_info, null);
        dialog.setView(root);
        etName = root.findViewById(R.id.et_name);
        etPhone = root.findViewById(R.id.et_phone);
        etName.setText(getSharedPreferences("afbName"));
        String phone = getSharedPreferences("afbPhone");
        if (StrUtil.isNotEmpty(phone)) {
            etName.setEnabled(false);
            etPhone.setEnabled(false);
            root.findViewById(R.id.tv_ok).setVisibility(View.GONE);
        }
        etPhone.setText(phone);
        root.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = etName.getText().toString();
                if (StrUtil.isEmpty(name)) {
                    showToast("名字不能为空");
                    return;
                }
                String phone = etPhone.getText().toString();
                if (StrUtil.isEmpty(phone)) {
                    showToast("支付宝账号不能为空");
                    return;
                }
                saveZfInfo();
            }
        });
        root.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
        alertDialog = dialog.create();
        alertDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
        alertDialog.setCancelable(false);
        alertDialog.show();
    }


    private void applyWithdrawal() {
        loading();
        final Map<String, Long> statsMap = AppUsageHelper.getStatsInfoOfYear(WithdrawalActivity.this);
        List<WithdrawalRecordVo> withdrawalRecordVoList = new ArrayList<>();
        for (Map.Entry<String, Long> entry : statsMap.entrySet()) {
            String name = DeviceUtils.getInstance().getAppName(this, entry.getKey());
            if ("unknown".equals(name)) {
                continue;
            }
            WithdrawalRecordVo withdrawalRecordVo1 = new WithdrawalRecordVo();
            withdrawalRecordVo1.setAppName(name);
            withdrawalRecordVo1.setAppPackage(entry.getKey());
            withdrawalRecordVo1.setAppUsrTime(AppUsageHelper.getTimeLengthName(entry.getValue()));
            withdrawalRecordVoList.add(withdrawalRecordVo1);
        }
        Gson gson = new Gson();
        withdrawalRecordVo.setWrDurationOfUse(gson.toJson(withdrawalRecordVoList));
        String oaid = DeviceUtils.getInstance().getOaId(this);
        withdrawalRecordVo.setOaid(oaid);
        withdrawalRecordVo.setToken(getSharedPreferences("deviceId"));
        //采集数据
        //是否分身
        boolean flag = VirtualApkCheckUtil.getSingleInstance().checkByCreateLocalServerSocket(DeviceUtils.getInstance().getPackageName(this));
        withdrawalRecordVo.setUdaSeparation(String.valueOf(flag ? 1 : 2));
        //是否模拟器
        flag = RiskUtils.getInstance().detectEmulator(this);
        withdrawalRecordVo.setUdaSimulator(String.valueOf(flag ? 1 : 2));
        //是否开启调试模式
        flag = DeviceUtils.getInstance().isDeveloperModeEnabled(this);
        withdrawalRecordVo.setUdaDebugMode(String.valueOf(flag ? 1 : 2));
        //是否USB调试模式
        flag = DeviceUtils.getInstance().isAdbEnabled(this);
        withdrawalRecordVo.setUdaUsbMode(String.valueOf(flag ? 1 : 2));
        //是否root
        flag = DeviceUtils.getInstance().isDeviceRooted(this);
        withdrawalRecordVo.setUdaRoot(String.valueOf(flag ? 1 : 2));
        //是否开启无障碍模式
        flag = DeviceUtils.getInstance().isAccessibilityServiceEnabled(this);
        withdrawalRecordVo.setUdaAccessibility(String.valueOf(flag ? 1 : 2));
        //是否开启VPN代理模式
        flag = DeviceUtils.getInstance().isWifiProxy();
        withdrawalRecordVo.setUdaVpnProxy(String.valueOf(flag ? 1 : 2));
        //手机应用总数
        List<PackageInfo> packageInfoList = DeviceUtils.getInstance().getAllApps(this);
        withdrawalRecordVo.setUdaAllApp(String.valueOf(ObjectUtil.isNotEmpty(packageInfoList) ? packageInfoList.size() : 0));
        List<UserDailyActivityVo> userDailyActivityVoList = new ArrayList<>();
        for (PackageInfo packageInfo : packageInfoList) {
            UserDailyActivityVo userDailyActivityVo = new UserDailyActivityVo();
            String name = DeviceUtils.getInstance().getAppName(this, packageInfo.packageName);
            userDailyActivityVo.setUdaPackage(packageInfo.packageName);
            userDailyActivityVo.setUdaAppName(name);
            userDailyActivityVo.setUdaVersionCode(packageInfo.versionName);
            userDailyActivityVoList.add(userDailyActivityVo);
        }
        // 将 User 对象转换为 JSON 字符串
        String jsonString = gson.toJson(userDailyActivityVoList);
        //应用JSON明细
        withdrawalRecordVo.setUdaAllAppDetail(jsonString);

        hucRequestInterfase.executeStr(this, null, HUCState.HUC_REQEUST_CODE_3, Request.Method.POST, UrlConfig.URL_WITHDRAWAL_USER, hucParameInterfase.getRequestParameter(withdrawalRecordVo), true);
    }

    private void showDescribe() {
        //判断提现账号
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        // dialog.setTitle("绑定姓名");
        View root = LayoutInflater.from(this).inflate(R.layout.pop_describe, null);
        dialog.setView(root);

        root.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
        alertDialog = dialog.create();
        alertDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
        alertDialog.setCancelable(false);
        alertDialog.show();
    }

    /**
     * 保存支付信息
     */
    private void saveZfInfo() {
        loading();
        ZfInfoVo zfInfoVo = new ZfInfoVo();
        zfInfoVo.setToken(getSharedPreferences("deviceId"));
        zfInfoVo.setName(etName.getText().toString());
        zfInfoVo.setPhone(etPhone.getText().toString());
        hucRequestInterfase.executeStr(this, null, HUCState.HUC_REQEUST_CODE_2, Request.Method.POST, UrlConfig.URL_USER_AFB_INFO, hucParameInterfase.getRequestParameter(zfInfoVo), true);
    }

    private void loadWithdrawalConfig() {
        loading();
        withdrawalVo.setToken(getSharedPreferences("deviceId"));
        hucRequestInterfase.executeStr(this, WithdrawalConfig.class, HUCState.HUC_REQEUST_CODE_1, Request.Method.POST, UrlConfig.URL_WITHDRAWAL_CONFIG, hucParameInterfase.getRequestParameter(withdrawalVo), false);

    }

    private void initAd() {

        String key = getSharedPreferences(RedisEnum.TA_KU.getKey());
        if (RedisEnum.TA_KU.getValue().equals(key)) {
                TaKuInterstitialAdWithdrawal taKuInterstitialAdWithdrawal = TaKuInterstitialAdWithdrawal.getInstance();
                taKuInterstitialAdWithdrawal.setToken(getSharedPreferences("deviceId"));
                taKuInterstitialAdWithdrawal.showAd(this);

                TaKuBannerAdWithdrawal taKuBannerAdWithdrawal = TaKuBannerAdWithdrawal.getInstance();
                taKuBannerAdWithdrawal.setToken(getSharedPreferences("deviceId"));
                taKuBannerAdWithdrawal.load(this,
                        StringSplit.splitOrNull(getSharedPreferences(RedisEnum.BANNER.getKey()),StrUtil.COMMA,1), flFll);
        } else {
                MediationTablePlaqueAd mediationTablePlaqueAd = MediationTablePlaqueAd.getInstance();
                mediationTablePlaqueAd.showCacheInterstitialFullAd(this, null);

                MediationFeedAd mediationFeedAd = MediationFeedAd.getInstance();
                mediationFeedAd.setFlFeed(flFll);
                mediationFeedAd.setActivity(this);
                mediationFeedAd.showCacheFeedAd();
        }

    }
}